package cn.xuqiudong.common.base.srpc.interceptor;

import cn.xuqiudong.common.base.web.intercept.log.TraceUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述:
 * Srpc 请求日志链路追踪拦截器
 *
 * @author Vic.xu
 * @since 2025-08-26 16:40
 */
public class SrpcLogTraceIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(TraceUtils.TRACE_ID);
        if (StringUtils.isNotBlank(traceId)) {
            TraceUtils.setTraceId(traceId);
        }  else {
            TraceUtils.createTraceId();
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        TraceUtils.destroyTraceId();
    }

}
